#include "app_controller.h"
#include "welcome.h"
#include "sys_info.h"
#include "ui_dashboard.h"
#include "welcome.h"

//定义两个全局变量
//变量一屏幕，接收createdash返回的屏幕
static lv_obj_t * scr = NULL;
//变量二,保存实时更新的控件并传输
static dashboard_widgets widgets;



/**
 * @brief 这个回调函数是仪表盘的数据源，负责刷新所有数据。
 */
//和事件响应回调函数一样，只不过这是个按定时器的回调函数
static void update_dashboard(lv_timer_t *t)
{
    //持续获取最新数据
    //获取cpu利用率
    double cpu_usage = get_cpu_usage();
    //获取内存情况
    mem_info_t mem = get_memory_info();
    //获取温度
    float temp = get_cpu_temperature();

    //将获取的数据更新到UI控件上
    //最后参数点开查看是(int32_t)类型
    lv_meter_set_indicator_value(widgets.cpu_meter,widgets.cpu_meter_indicator,(int32_t)cpu_usage);
    lv_label_set_text_fmt(widgets.cpu_meter_label,"%d%%",(int)cpu_usage);

    //更新cpu历史曲线
    //lv_coord_t点开查看是(int16_t)类型
    lv_chart_set_next_value(widgets.cpu_chart,widgets.cpu_chart_series,(int16_t)cpu_usage);

    //更新内存条和标签
    //判断是否读取到了内存值
    if (mem.total_kb > 0)
    {
        //lv_bar_set_value传递的值必须是int32_t 类型
        int32_t mem_percent = 100 * (mem.total_kb-mem.available_kb)/mem.total_kb;
        //内存使用情况为高帧率数据更新立即跳变所以不启用动画
        lv_bar_set_value(widgets.mem_bar,mem_percent,LV_ANIM_OFF);

        //更新内存的标签值，并且改为GB提高可读性
        lv_label_set_text_fmt(widgets.mem_label,"RAM:%.2f/%.2f GB",
            (double)(mem.total_kb-mem.available_kb)/(1024.0*1024.0),
            (double)(mem.total_kb)/(1024.0*1024.0));

    }

    //更新温度标签
    lv_label_set_text_fmt(widgets.temp_label,"Temp: %.2f C", temp);
    


}



//创建按钮回调函数，点击按钮就会切换到下一个页面
void go_to_dashboard(lv_event_t * e)
{
    

    lv_event_code_t code = lv_event_get_code(e);
    if (scr == NULL && code == LV_EVENT_CLICKED)
    {
        LOG_TRACE();
        scr = create_dashboard_screen(&widgets);

        LOG_TRACE();
        //启动定时器不停刷新数据
        //调用这个定时器函数，该函数会每隔一段时间调用里面的回调函数
        //lv_timer_t * lv_timer_create(lv_timer_cb_t timer_xcb, uint32_t period, void * user_data)
        lv_timer_create(update_dashboard,(uint32_t)500,NULL);
        LOG_TRACE();

        
        //判断事件为点击事件后切换页面
        
        lv_scr_load_anim(scr,LV_SCR_LOAD_ANIM_MOVE_LEFT,300,0,false);
        LOG_TRACE();
    }
    
}


void start_sys_monitor_app(void)
{
    create_welcome_screen();

}
